﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Lm.Common.Xml
{
    public class XmlSerializer
    {
        /// <summary>
        /// 把对象序列化成xml字符串
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public string Serialize(object obj)
        {
            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(obj.GetType());
            StringBuilder sb = new StringBuilder();
            serializer.Serialize(new System.IO.StringWriter(sb), obj);
            return sb.ToString();
        }
        /// <summary>
        /// 把xml字符串解析成对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="xml"></param>
        /// <returns></returns>
        public T Deserialize<T>(string xml)
        {
            try
            {
                System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
                return (T)serializer.Deserialize(new System.IO.StringReader(xml));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
